from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QLabel, 
                                 QPushButton, QTextEdit, QMessageBox)
from core.rfid_manager import RFIDManager

class OperationPage(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.rfid_manager = RFIDManager()
        self.data = {}
        self.setup_ui()

    def setup_ui(self):
        layout = QVBoxLayout(self)
        
        # 标题
        title = QLabel("RFID操作")
        title.setStyleSheet("font-size: 24px; margin: 20px;")
        layout.addWidget(title)

        # 信息显示区域
        self.info_display = QTextEdit()
        self.info_display.setReadOnly(True)
        layout.addWidget(self.info_display)

        # 操作按钮
        write_btn = QPushButton("写入RFID卡")
        write_btn.clicked.connect(self.write_card)
        layout.addWidget(write_btn)

        read_btn = QPushButton("读取RFID卡")
        read_btn.clicked.connect(self.read_card)
        layout.addWidget(read_btn)

        # 返回按钮
        back_btn = QPushButton("返回")
        back_btn.clicked.connect(lambda: self.parent().switch_to_page(1))
        layout.addWidget(back_btn)

        layout.addStretch()

    def set_data(self, data):
        """设置要写入的数据"""
        self.data = data
        self.update_display()

    def update_display(self):
        """更新显示的信息"""
        display_text = "当前信息：\n"
        for key, value in self.data.items():
            display_text += f"{key}: {value}\n"
        self.info_display.setText(display_text)

    def write_card(self):
        """写入RFID卡"""
        try:
            if self.rfid_manager.write_card(self.data):
                QMessageBox.information(self, "成功", "数据写入成功")
            else:
                QMessageBox.critical(self, "错误", "数据写入失败")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"写入过程出错: {str(e)}")

    def read_card(self):
        """读取RFID卡"""
        try:
            data = self.rfid_manager.read_card()
            if data:
                self.data = data
                self.update_display()
                QMessageBox.information(self, "成功", "数据读取成功")
            else:
                QMessageBox.critical(self, "错误", "数据读取失败")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"读取过程出错: {str(e)}") 